package com.leyou.service;

import com.leyou.client.BrandClient;
import com.leyou.client.CategoryClient;
import com.leyou.client.GoodsClient;
import com.leyou.client.SpecificationClient;
import com.leyou.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;

    @Autowired
    private TemplateEngine templateEngine;

    public static final String destPath = "E:/nginx-1.12.2/html/item";

    public Map<String,Object> loadModel(Long id) {
        Map<String,Object> map = new HashMap();
        Spu spu = goodsClient.getSpuById(id);
        List<Sku> skus = spu.getSkus();
        SpuDetail detail = spu.getSpuDetail();
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        List<Category> categories = categoryClient.queryNameByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));
        List<SpecGroup> specs = specificationClient.queryGroupByCid(spu.getCid3());

        map.put("spu",spu);
        map.put("skus",skus);
        map.put("detail",detail);
        map.put("brand",brand);
        map.put("categories",categories);
        map.put("specs",specs);
        return map;
    }

    public void createHtml(Long id) {
        // 上下文
        Context context = new Context();
        context.setVariables(loadModel(id));
        // 输出流
        File dest = new File(destPath, id + ".html");
        if (dest.exists()) {
            dest.delete();
        }
        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
            // 生成html，第一个参数是thymeleaf页面下的原型名称
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("[静态页服务]：生成静态页异常", e);
        }
    }

}
